95E - Lucky Country - CodeForces Solution


dp dsu graphs *2500

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;

const int MAXN = 1e5 + 1;
vector<int> adj[MAXN];
vector<bool> visited(MAXN);
vector<int> compCount(MAXN), dp(MAXN);

int dfs(int v, int p) {
  if (visited[v]) return 0;
  visited[v] = true;
  int count = 1;
  for (int i : adj[v]) {
    if (i != p) {
      count += dfs(i, v);
    }
  }
  return count;
}

bool lucky(int x) {
  if (x == 0) return false;
  while (x > 0) {
    if (x % 10 != 4 && x % 10 != 7) {
      return false;
    }
    x /= 10;
  }
  return true;
}

int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int a, b;
    cin >> a >> b;
    adj[--a].push_back(--b);
    adj[b].push_back(a);
  }
  for (int i = 0; i < n; i++) {
    if (!visited[i]) {
      compCount[dfs(i, -1)]++;
    }
  }

  for (int i = 1; i <= n; i++) {
    dp[i] = MAXN;
  }
  for (int i = 1; i <= n; i++) {
    if (compCount[i] > 0) {
      for (int mod = 0; mod < i; mod++) {
        deque<pair<int,int>> dq;
        int edges = 0;
        for (int j = mod; j <= n; j += i) {
          while (!dq.empty() && dp[j] - edges <= dq.back().first) {
            dq.pop_back();
          }
          dq.push_back({dp[j] - edges, j});
          dp[j] = dq.front().first + edges;
          if (dq.front().second == j - i * compCount[i]) {
            dq.pop_front();
          }
          edges++;
        }
      }
    }
  }
  
  int ans = MAXN;
  for (int i = 1; i < MAXN; i++) {
    if (lucky(i) && dp[i] > 0) {
      ans = min(ans, dp[i]);
    }
  }
  if (ans != MAXN) {
    cout << ans-1 << endl;
  } else {
    cout << -1 << endl;
  }
  
  return 0;
}

  	 	 		 	   			      		  					


Comments

Submit
0 Comments
More Questions

721B - Passwords
1263D - Secret Passwords
1371B - Magical Calendar
1726E - Almost Perfect
1360C - Similar Pairs
900A - Find Extra One
1093D - Beautiful Graph
748A - Santa Claus and a Place in a Class
1511B - GCD Length
676B - Pyramid of Glasses
597A - Divisibility
1632A - ABC
1619D - New Year's Problem
242B - Big Segment
938A - Word Correction
159C - String Manipulation 10
258A - Little Elephant and Bits
1536C - Diluc and Kaeya
1428C - ABBB
1557A - Ezzat and Two Subsequences
255A - Greg's Workout
1059A - Cashier
1389C - Good String
1561A - Simply Strange Sort
1337B - Kana and Dragon Quest game
137C - History
1443C - The Delivery Dilemma
6C - Alice Bob and Chocolate
1077C - Good Array
285B - Find Marble